<template>
  <div class="mod-demo-echarts">

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
          <div id="J_chartLineBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="24">
        <el-card>
          <div id="J_chartBarBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="trPie" class="chart-box"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div id="J_chartScatterBox" class="chart-box"></div>
        </el-card>
      </el-col>
      <!-- 新增摄像头模块 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <div style="font-size: 30px">打开电脑摄像头</div>
          </template>
          <video id="webcamVideo" class="chart-box" autoplay></video>
          <el-button @click="openWebcam">打开摄像头</el-button>
          <el-button @click="closeWebcam">关闭摄像头</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import echarts from 'echarts'
  export default {
    data () {
      return {
        chartLine: null,
        chartBar: null,
        chartPie: null,
        chartScatter: null,
        xAxisData: []
      }
    },
    mounted () {
      this.initChartLine()
      this.initChartBar()
      this.initChartPie()
      this.initChartScatter()
    },
    activated () {
      // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
      if (this.chartLine) {
        this.chartLine.resize()
      }
      if (this.chartBar) {
        this.chartBar.resize()
      }
      if (this.chartPie) {
        this.chartPie.resize()
      }
      if (this.chartScatter) {
        this.chartScatter.resize()
      }
    },
    methods: {
      // 柱状图
      initChartBar () {
        var option = {
          title: {
            text: '棉花生长和质量情况'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['株高', '茎粗', '叶片数', '第一果枝节高度', '籽棉产量', '伸长率', '衣指', '花数']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: this.xAxisData,
              axisLabel: {
                rotate: 45, // 将标签旋转45度
                fontSize: 10 // 检查字体大小是否合适
              }
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '株高',
              type: 'bar',
              data: []
            },
            {
              name: '茎粗',
              type: 'bar',
              stack: '茎粗',
              data: []
            },
            {
              name: '叶片数',
              type: 'bar',
              stack: '叶片数',
              data: []
            },
            {
              name: '第一果枝节高度',
              type: 'bar',
              stack: '第一果枝节高度',
              data: []
            },
            {
              name: '籽棉产量',
              type: 'bar',
              data: [],
              markLine: {
                lineStyle: {
                  normal: {
                    type: 'dashed'
                  }
                },
                data: [
                  [{ type: 'min' }, { type: 'max' }]
                ]
              }
            },
            {
              name: '伸长率',
              type: 'bar',
              barWidth: 5,
              stack: '伸长率',
              data: []
            },
            {
              name: '衣指',
              type: 'bar',
              stack: '衣指',
              data: []
            },
            {
              name: '花数',
              type: 'bar',
              stack: '花数',
              data: []
            }
          ]
        }
        this.chartBar = echarts.init(document.getElementById('J_chartBarBox'))
        this.chartBar.setOption(option)
        this.$http({
          url: this.$http.adornUrl('/mh/growth/growthbar'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            // let xAxisData = []
            let mhHeight = []
            let mhJc = []
            let mhYps = []
            let mhDygzjgd = []
            let mhZmcl = []
            let mhSzl = []
            let mhYz = []
            let mhHs = []
            data.data.forEach(item => {
              this.xAxisData.push(item.mhBh)
              mhHeight.push(item.mhHeight)
              mhJc.push(item.mhJc)
              mhYps.push(item.mhYps)
              mhDygzjgd.push(item.mhDygzjgd)
              mhZmcl.push(item.mhZmcl)
              mhSzl.push(item.mhSzl)
              mhYz.push(item.mhYz)
              mhHs.push(item.mhHs)
            })
            option.xAxis.data = this.xAxisData
            // console.log('生长质量：' + JSON.stringify(option.xAxis.data))
            option.series[0].data = mhHeight
            option.series[1].data = mhJc
            option.series[2].data = mhYps
            option.series[3].data = mhDygzjgd
            option.series[4].data = mhZmcl
            option.series[5].data = mhSzl
            option.series[6].data = mhYz
            option.series[7].data = mhHs
            // console.log('准备设置的选项：', option)
            this.chartBar.setOption(option)
            // console.log('设置选项后的x轴数据：', this.chartBar.getOption())
          } else {
            console.log('未找到 dataForEcharts 属性')
          }
        })
        window.addEventListener('resize', () => {
          this.chartBar.resize()
        })
      },
      // 散点图
      initChartScatter () {
        var option = {
          backgroundColor: new echarts.graphic.RadialGradient(0.3, 0.3, 0.8, [
            { offset: 0, color: '#f7f8fa' },
            { offset: 1, color: '#cdd0d5' }
          ]),
          title: {
            text: '幼虫数(卵虫数)与总虫数的关系'
          },
          legend: {
            right: 10,
            data: ['幼虫数', '卵虫数']
          },
          xAxis: {
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            }
          },
          yAxis: {
            splitLine: {
              lineStyle: {
                type: 'dashed'
              }
            },
            scale: true
          },
          series: [
            {
              name: '幼虫数',
              data: [],
              type: 'scatter',
              symbolSize: function (data) {
                return Math.sqrt(data[2]) / 5e2
              },
              label: {
                emphasis: {
                  show: true,
                  formatter: function (param) {
                    return param.data[3]
                  },
                  position: 'top'
                }
              },
              itemStyle: {
                normal: {
                  shadowBlur: 10,
                  shadowColor: 'rgba(120, 36, 50, 0.5)',
                  shadowOffsetY: 5,
                  color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                    { offset: 0, color: 'rgb(251, 118, 123)' },
                    { offset: 1, color: 'rgb(204, 46, 72)' }
                  ])
                }
              }
            },
            {
              name: '卵虫数',
              data: [],
              type: 'scatter',
              symbolSize: function (data) {
                return Math.sqrt(data[2]) / 5e2
              },
              label: {
                emphasis: {
                  show: true,
                  formatter: function (param) {
                    return param.data[3]
                  },
                  position: 'top'
                }
              },
              itemStyle: {
                normal: {
                  shadowBlur: 10,
                  shadowColor: 'rgba(25, 100, 150, 0.5)',
                  shadowOffsetY: 5,
                  color: new echarts.graphic.RadialGradient(0.4, 0.3, 1, [
                    { offset: 0, color: 'rgb(129, 227, 238)' },
                    { offset: 1, color: 'rgb(25, 183, 207)' }
                  ])
                }
              }
            }
          ]
        }
        this.chartScatter = echarts.init(document.getElementById('J_chartScatterBox'))
        this.chartScatter.setOption(option)
        this.$http({
          url: this.$http.adornUrl('/mh/bc/bcnum'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            let bcYcs = [] // 幼虫数
            let bcLs = [] // 卵数
            data.data.forEach(item => {
              bcYcs.push([item.bcZcl, item.bcYcs, 200000000, item.mhBh])
              bcLs.push([item.bcZcl, item.bcLs, 100000000, item.mhBh])
            })
            console.log('病虫数据：' + JSON.stringify(data.data))
            option.series[0].data = bcYcs
            option.series[1].data = bcLs
            this.chartScatter.setOption(option)
          } else {
            console.log('未找到 dataForEcharts 属性')
          }
        })
        window.addEventListener('resize', () => {
          this.chartPie.resize()
        })
      },
      // 折线图
      initChartLine () {
        var option = {
          'title': {
            'text': '天气折线图堆叠'
          },
          'tooltip': {
            'trigger': 'axis'
          },
          'legend': {
            // eslint-disable-next-line standard/array-bracket-even-spacing
            'data': [ '气温', '湿度', '风速', '高温天气', '降水量']
          },
          'grid': {
            'left': '3%',
            'right': '4%',
            'bottom': '3%',
            'containLabel': true
          },
          'toolbox': {
            'feature': {
              'saveAsImage': { }
            }
          },
          'xAxis': {
            'type': 'category',
            'boundaryGap': false,
            'data': []
          },
          'yAxis': {
            'type': 'value'
          },
          'series': [
            {
              'name': '气温',
              'type': 'line',
              'stack': '总量',
              'data': []
            },
            {
              'name': '湿度',
              'type': 'line',
              'stack': '总量',
              'data': []
            },
            {
              'name': '风速',
              'type': 'line',
              'stack': '总量',
              'data': []
            },
            {
              'name': '高温天气',
              'type': 'line',
              'stack': '总量',
              'data': []
            },
            {
              'name': '降水量',
              'type': 'line',
              'stack': '总量',
              'data': [ 120, 132, 101, 124, 90, 110, 100, 110 ]
            }
          ]
        }
        this.chartLine = echarts.init(document.getElementById('J_chartLineBox'))
        this.chartLine.setOption(option)
        this.$http({
          url: this.$http.adornUrl('/mh/weather/temperature'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            let xAxisData = []    // 当前一周的时间范围
            let temperatureData = []  // 温度
            let precipitation = [] // 湿度
            let windSpeed = []   // 风速
            let gwDays = []  // 高温天气
            data.data.forEach(item => {
              xAxisData.push(item.recordDate)
              temperatureData.push(item.temperature)
              precipitation.push(item.precipitation)
              if (typeof item.windSpeed === 'string') {
                let match = item.windSpeed.match(/(\d+)/)
                if (match) {
                  windSpeed.push(parseInt(match[1], 10))
                } else {
                  // 如果没有匹配到数字，根据实际需求处理，这里设为0
                  windSpeed.push(0)
                }
              } else {
                // 如果不是字符串类型（假设是数值类型），直接添加
                windSpeed.push(item.windSpeed)
              }
              gwDays.push(item.gwDays)
            })
            console.log('天气数据：' + JSON.stringify(data.data))
            option.xAxis.data = xAxisData
            option.series[0].data = temperatureData // 温度
            option.series[1].data = precipitation // 湿度
            option.series[2].data = windSpeed // 风速
            option.series[3].data = gwDays  // 高温天气
            this.chartLine.setOption(option)
          } else {
            console.log('未找到 dataForEcharts 属性')
          }
        })
        window.addEventListener('resize', () => {
          this.chartLine.resize()
        })
      },
      // 饼状图
      initChartPie () {
        const pieOption = {
          // backgroundColor: 'white', // 将背景颜色设置为白色
          backgroundColor: '#f7f8fa',
          title: {
            text: '有机质含量图',
            left: 'center',
            top: 20,
            textStyle: {
              color: '#ccc'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          visualMap: {
            show: false,
            min: 80,
            max: 600,
            inRange: {
              colorLightness: [0, 1]
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'top',
            data: []
          },
          series: [
            {
              name: '含量比',
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: []
            }
          ]
        }
        const myChartDom = document.getElementById('trPie')
        const myChart = echarts.init(myChartDom)
        myChart.setOption(pieOption)
        this.$http({
          url: this.$http.adornUrl('/mh/tr/yjzhlpie'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            const dataForEcharts = Object.entries(data.data).map(([key, value]) => ({
              value: value,
              name: key
            }))
            console.log('土壤分布图：' + JSON.stringify(dataForEcharts))
            pieOption.series[0].data = dataForEcharts
            pieOption.legend.data = dataForEcharts.map(item => item.name)
            myChart.setOption(pieOption)
          } else {
            console.log('未找到 dataForEcharts 属性')
          }
        })
      },
      // 打开摄像头
      openWebcam () {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: true })
            .then((stream) => {
              const video = document.getElementById('webcamVideo')
              video.srcObject = stream
              this.mediaStream = stream
            })
            .catch((error) => {
              if (error.name === 'NotAllowedError') {
                alert('你拒绝了摄像头访问权限，请在浏览器设置中允许访问摄像头后重试。')
              } else {
                console.error('无法访问摄像头:', error)
              }
            })
        }
      },
      // 关闭摄像头
      closeWebcam () {
        if (this.mediaStream) {
          const tracks = this.mediaStream.getTracks()
          tracks.forEach((track) => {
            track.stop()
          })
          const video = document.getElementById('webcamVideo')
          video.srcObject = null
          this.mediaStream = null
        }
      }
    }
  }
</script>

<style lang="scss">
  .mod-demo-echarts {
    > .el-alert {
      margin-bottom: 10px;
    }
    > .el-row {
      margin-top: -10px;
      margin-bottom: -10px;
      .el-col {
        padding-top: 10px;
        padding-bottom: 10px;
      }
    }
    .chart-box {
      min-height: 400px;
    }
  }
  /* 为摄像头视频添加样式 */
  #webcamVideo {
    width: 100%;
    height: 100%;
    object-fit: cover;
    background-color: black; /* 设置背景颜色为黑色 */
  }
</style>
